import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import Header from './Header';
import PhotoPreview from './PhotoPreview';
import './Timeline.css';

const Timeline = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(true);
  const [timelineData, setTimelineData] = useState([]);
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
  const [viewMode, setViewMode] = useState('grid'); // 'grid' or 'list'
  const [showPhotoPreview, setShowPhotoPreview] = useState(false);
  const [selectedPhoto, setSelectedPhoto] = useState(null);
  const [previewPhotoIndex, setPreviewPhotoIndex] = useState(0);
  const [currentMonthPhotos, setCurrentMonthPhotos] = useState([]);

  // Check for mock authentication
  const isAuthenticated = !!localStorage.getItem('mockAuthToken');
  const user = isAuthenticated ? JSON.parse(localStorage.getItem('mockUser') || '{}') : null;

  useEffect(() => {
    // Simulate loading timeline data
    setTimeout(() => {
      // Get albums from localStorage
      const userAlbums = JSON.parse(localStorage.getItem('userAlbums') || '[]');
      
      // Mock data for system albums
      const systemAlbums = [
        {
          id: 1,
          name: '夏日假期',
          photos: [
            { id: 101, name: '海滩日出.jpg', date: '2023-07-15', thumbnail: '🌅' },
            { id: 102, name: '沙滩排球.jpg', date: '2023-07-16', thumbnail: '🏐' },
            { id: 103, name: '海边烧烤.jpg', date: '2023-07-17', thumbnail: '🍖' },
            { id: 104, name: '日落余晖.jpg', date: '2023-07-18', thumbnail: '🌇' },
            { id: 105, name: '海浪拍岸.jpg', date: '2023-07-19', thumbnail: '🌊' },
            { id: 106, name: '沙滩城堡.jpg', date: '2023-07-20', thumbnail: '🏰' }
          ]
        },
        {
          id: 2,
          name: '家庭聚会',
          photos: [
            { id: 201, name: '全家福.jpg', date: '2023-06-20', thumbnail: '👨‍👩‍👧‍👦' },
            { id: 202, name: '生日蛋糕.jpg', date: '2023-06-21', thumbnail: '🎂' },
            { id: 203, name: '家庭晚餐.jpg', date: '2023-06-22', thumbnail: '🍽️' },
            { id: 204, name: '游戏时光.jpg', date: '2023-06-23', thumbnail: '🎮' },
            { id: 205, name: '庭院烧烤.jpg', date: '2023-06-24', thumbnail: '🔥' },
            { id: 206, name: '合影留念.jpg', date: '2023-06-25', thumbnail: '📸' }
          ]
        },
        {
          id: 3,
          name: '城市探索',
          photos: [
            { id: 301, name: '城市天际线.jpg', date: '2023-05-10', thumbnail: '🏙️' },
            { id: 302, name: '街头艺术.jpg', date: '2023-05-11', thumbnail: '🎨' },
            { id: 303, name: '咖啡时光.jpg', date: '2023-05-12', thumbnail: '☕' },
            { id: 304, name: '夜景灯光.jpg', date: '2023-05-13', thumbnail: '✨' },
            { id: 305, name: '建筑之美.jpg', date: '2023-05-14', thumbnail: '🏛️' },
            { id: 306, name: '城市公园.jpg', date: '2023-05-15', thumbnail: '🌳' }
          ]
        },
        {
          id: 4,
          name: '自然风光',
          photos: [
            { id: 401, name: '山川河流.jpg', date: '2023-04-05', thumbnail: '⛰️' },
            { id: 402, name: '森林小径.jpg', date: '2023-04-06', thumbnail: '🌲' },
            { id: 403, name: '湖泊倒影.jpg', date: '2023-04-07', thumbnail: '🏞️' },
            { id: 404, name: '瀑布奇观.jpg', date: '2023-04-08', thumbnail: '💧' },
            { id: 405, name: '日出东方.jpg', date: '2023-04-09', thumbnail: '🌅' },
            { id: 406, name: '星空璀璨.jpg', date: '2023-04-10', thumbnail: '⭐' }
          ]
        },
        {
          id: 5,
          name: '美食记录',
          photos: [
            { id: 501, name: '精致甜点.jpg', date: '2023-03-15', thumbnail: '🧁' },
            { id: 502, name: '家常菜.jpg', date: '2023-03-16', thumbnail: '🍲' },
            { id: 503, name: '异国料理.jpg', date: '2023-03-17', thumbnail: '🍱' },
            { id: 504, name: '街头小吃.jpg', date: '2023-03-18', thumbnail: '🥟' },
            { id: 505, name: '咖啡拉花.jpg', date: '2023-03-19', thumbnail: '☕' },
            { id: 506, name: '水果拼盘.jpg', date: '2023-03-20', thumbnail: '🍉' }
          ]
        },
        {
          id: 6,
          name: '旅行记忆',
          photos: [
            { id: 601, name: '机场出发.jpg', date: '2023-02-10', thumbnail: '✈️' },
            { id: 602, name: '异国风情.jpg', date: '2023-02-11', thumbnail: '🗽' },
            { id: 603, name: '当地美食.jpg', date: '2023-02-12', thumbnail: '🍜' },
            { id: 604, name: '名胜古迹.jpg', date: '2023-02-13', thumbnail: '🏛️' },
            { id: 605, name: '民俗文化.jpg', date: '2023-02-14', thumbnail: '🎭' },
            { id: 606, name: '旅行合影.jpg', date: '2023-02-15', thumbnail: '📸' }
          ]
        }
      ];
      
      // Combine all albums
      const allAlbums = [...userAlbums, ...systemAlbums];
      
      // Extract all photos and organize by date
      const allPhotos = [];
      allAlbums.forEach(album => {
        if (album.photos && album.photos.length > 0) {
          album.photos.forEach(photo => {
            allPhotos.push({
              ...photo,
              albumId: album.id,
              albumName: album.name
            });
          });
        }
      });
      
      // Group photos by year and month
      const timelineMap = {};
      allPhotos.forEach(photo => {
        const date = new Date(photo.date);
        const year = date.getFullYear();
        const month = date.getMonth();
        
        if (!timelineMap[year]) {
          timelineMap[year] = {};
        }
        
        if (!timelineMap[year][month]) {
          timelineMap[year][month] = [];
        }
        
        timelineMap[year][month].push(photo);
      });
      
      // Convert to timeline data format
      const timelineDataArray = [];
      Object.keys(timelineMap).sort((a, b) => b - a).forEach(year => {
        const yearData = {
          year: parseInt(year),
          months: [],
          totalPhotos: 0
        };
        
        Object.keys(timelineMap[year]).sort((a, b) => b - a).forEach(month => {
          const monthPhotos = timelineMap[year][month];
          const monthData = {
            month: parseInt(month),
            monthName: new Date(year, month, 1).toLocaleString('default', { month: 'long' }),
            photoCount: monthPhotos.length,
            photos: monthPhotos.slice(0, 6) // Show only first 6 photos
          };
          
          yearData.months.push(monthData);
          yearData.totalPhotos += monthPhotos.length;
        });
        
        timelineDataArray.push(yearData);
      });
      
      setTimelineData(timelineDataArray);
      setIsLoading(false);
    }, 1000);
  }, []);

  const handlePhotoClick = (photoId) => {
    navigate(`/photo/${photoId}`);
  };

  const handleMonthClick = (year, month) => {
    navigate(`/timeline/${year}/${month}`);
  };

  const handlePhotoPreview = (photo, index, allMonthPhotos) => {
    setSelectedPhoto(photo);
    setPreviewPhotoIndex(index);
    setCurrentMonthPhotos(allMonthPhotos);
    setShowPhotoPreview(true);
  };

  const handleClosePhotoPreview = () => {
    setShowPhotoPreview(false);
    setSelectedPhoto(null);
    setPreviewPhotoIndex(0);
    setCurrentMonthPhotos([]);
  };

  const handleNextPhoto = () => {
    if (previewPhotoIndex >= currentMonthPhotos.length - 1) return;
    
    const nextIndex = previewPhotoIndex + 1;
    const nextPhoto = currentMonthPhotos[nextIndex];
    setSelectedPhoto(nextPhoto);
    setPreviewPhotoIndex(nextIndex);
  };

  const handlePrevPhoto = () => {
    if (previewPhotoIndex <= 0) return;
    
    const prevIndex = previewPhotoIndex - 1;
    const prevPhoto = currentMonthPhotos[prevIndex];
    setSelectedPhoto(prevPhoto);
    setPreviewPhotoIndex(prevIndex);
  };

  const handleDownloadPhoto = () => {
    if (!selectedPhoto) return;
    
    // Create a temporary link element to download the photo
    const link = document.createElement('a');
    link.href = selectedPhoto.thumbnail;
    link.download = selectedPhoto.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const filteredData = timelineData.filter(yearData => yearData.year === selectedYear);

  if (!isAuthenticated) {
    navigate('/auth');
    return null;
  }

  return (
    <div className="timeline-container">
      <Header />
      <div className="timeline-content">
        <div className="timeline-header">
          <h1 className="timeline-title">{t('timeline.title')}</h1>
          <p className="timeline-subtitle">{t('timeline.subtitle')}</p>
        </div>

        {/* Timeline Controls */}
        <div className="timeline-controls">
          <div className="year-selector">
            <label>{t('timeline.selectYear')}:</label>
            <select 
              value={selectedYear} 
              onChange={(e) => setSelectedYear(parseInt(e.target.value))}
              className="year-select"
            >
              {timelineData.map(yearData => (
                <option key={yearData.year} value={yearData.year}>
                  {yearData.year} ({yearData.totalPhotos} {t('timeline.photos')})
                </option>
              ))}
            </select>
          </div>
          
          <div className="view-mode-toggle">
            <button 
              className={`view-mode-btn ${viewMode === 'grid' ? 'active' : ''}`}
              onClick={() => setViewMode('grid')}
            >
              <span className="view-icon">⊞</span>
              {t('timeline.gridView')}
            </button>
            <button 
              className={`view-mode-btn ${viewMode === 'list' ? 'active' : ''}`}
              onClick={() => setViewMode('list')}
            >
              <span className="view-icon">☰</span>
              {t('timeline.listView')}
            </button>
          </div>
        </div>

        {isLoading ? (
          <div className="timeline-loading">
            <div className="loading-spinner"></div>
            <p>{t('timeline.loading')}</p>
          </div>
        ) : (
          <div className="timeline-body">
            {filteredData.length > 0 ? (
              filteredData.map(yearData => (
                <div key={yearData.year} className="timeline-year">
                  <h2 className="year-title">{yearData.year}</h2>
                  <div className="year-stats">
                    {yearData.totalPhotos} {t('timeline.photosInYear')}
                  </div>
                  
                  <div className={`timeline-months ${viewMode}-view`}>
                    {yearData.months.map(monthData => (
                      <div key={`${yearData.year}-${monthData.month}`} className="timeline-month">
                        <div className="month-header">
                          <h3 className="month-title">{monthData.monthName}</h3>
                          <span className="photo-count">{monthData.photoCount} {t('timeline.photos')}</span>
                        </div>
                        
                        {viewMode === 'grid' ? (
                          <div className="photo-grid">
                            {monthData.photos.map((photo, index) => (
                              <div
                                key={photo.id}
                                className="photo-item"
                                title={photo.name}
                              >
                                <div className="photo-thumbnail" onClick={() => handlePhotoPreview(photo, index, monthData.photos)}>
                                  {photo.thumbnail.startsWith('data:') ? (
                                    <img src={photo.thumbnail} alt={photo.name} />
                                  ) : (
                                    <span className="photo-emoji">{photo.thumbnail}</span>
                                  )}
                                </div>
                                <div className="photo-info">
                                  <div className="photo-date">{photo.date}</div>
                                  {photo.albumName && (
                                    <div className="photo-album" onClick={() => navigate(`/albums/${photo.albumId}`)}>
                                      {photo.albumName}
                                    </div>
                                  )}
                                </div>
                              </div>
                            ))}
                            {monthData.photoCount > 6 && (
                              <div
                                className="more-photos"
                                onClick={() => handleMonthClick(yearData.year, monthData.month)}
                              >
                                <span>+{monthData.photoCount - 6}</span>
                                <span>{t('timeline.more')}</span>
                              </div>
                            )}
                          </div>
                        ) : (
                          <div className="photo-list">
                            {monthData.photos.map((photo, index) => (
                              <div
                                key={photo.id}
                                className="photo-list-item"
                              >
                                <div className="photo-thumbnail" onClick={() => handlePhotoPreview(photo, index, monthData.photos)}>
                                  {photo.thumbnail.startsWith('data:') ? (
                                    <img src={photo.thumbnail} alt={photo.name} />
                                  ) : (
                                    <span className="photo-emoji">{photo.thumbnail}</span>
                                  )}
                                </div>
                                <div className="photo-info" onClick={() => handlePhotoPreview(photo, index, monthData.photos)}>
                                  <h4 className="photo-name">{photo.name}</h4>
                                  <p className="photo-date">{photo.date}</p>
                                  {photo.albumName && (
                                    <div className="photo-album" onClick={(e) => {
                                      e.stopPropagation();
                                      navigate(`/albums/${photo.albumId}`);
                                    }}>
                                      {photo.albumName}
                                    </div>
                                  )}
                                </div>
                              </div>
                            ))}
                            {monthData.photoCount > 6 && (
                              <div
                                className="view-more-btn"
                                onClick={() => handleMonthClick(yearData.year, monthData.month)}
                              >
                                {t('timeline.viewAll')} {monthData.photoCount} {t('timeline.photos')}
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              ))
            ) : (
              <div className="no-photos">
                <div className="no-photos-icon">📷</div>
                <h3>{t('timeline.noPhotos')}</h3>
                <p>{t('timeline.noPhotosMessage')}</p>
                <button 
                  className="upload-btn"
                  onClick={() => navigate('/upload')}
                >
                  {t('timeline.uploadPhotos')}
                </button>
              </div>
            )}
          </div>
        )}
        
        {/* Photo Preview Modal */}
        {showPhotoPreview && currentMonthPhotos.length > 0 && (
          <PhotoPreview
            photos={currentMonthPhotos}
            currentIndex={previewPhotoIndex}
            onClose={handleClosePhotoPreview}
          />
        )}
      </div>
    </div>
  );
};

export default Timeline;